const CloudDBZoneWrapper = require('./CloudDBZoneWrapper')

const cardHandler = async function (event, context, callback, logger) {
  // 获取用户信息
  // 然后获取用户唯一标识
  // 添加一条银行卡记录，包含卡号，所属银行，持卡人姓名，过期时间，ccv
  try {
    const cloudDBZoneWrapper = new CloudDBZoneWrapper(logger);
    const { action, payload } = JSON.parse(event.body || '{}')

    // 执行添加银行卡逻辑
    if (action === 'add') {
      await cloudDBZoneWrapper.add(payload)
      return callback({
        status: true
      })
    }

    // 执行查询逻辑
    if (action === 'query') {
      const queryResult = await cloudDBZoneWrapper.query(payload);
      const data = queryResult.map(a => Object.fromEntries(a.getFieldMap()))

      return callback({
        status: true,
        data
      });
    }

    callback({
      status: false,
      errMsg: 'no valid action'
    })

  } catch(e) {
    callback({
      status: false,
      errMsg: e.message
    })
  }
};

export { cardHandler };